package com.efun.center.filter;

import com.efun.center.datasource.BindingDataSourceKey;
import com.efun.center.datasource.DataSourceMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*", filterName = "dsFilter")
public class DataSourceFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String area = request.getParameter("area");
        if (StringUtils.isEmpty(area) || area.toLowerCase().equals("null") || area.toLowerCase().equals("undefined")) {
            HttpServletRequest req = (HttpServletRequest) request;
            if (!req.getRequestURI().equals("/favicon.ico")) {
                logger.info(req.getRequestURI() + " contains no area parameter!");
            }
        } else {
            if (DataSourceMap.getDataSourceMap(area) != null) {
                BindingDataSourceKey.setDataSourceToken(area);
                logger.info("change datasource to " + BindingDataSourceKey.getDataSourceToken());
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        BindingDataSourceKey.clearDataSourceToken();
    }

}
